﻿using System.Collections.Generic;
using System.Timers;
using System.ComponentModel;

namespace WCFServerService
{
	public class ClientQueueManagerBO
	{
		#region Members

		private Timer notificationTimer;

		static ClientQueue clientQueue = null;
		
		static readonly object lockObject = new object();

		#endregion

		public ClientQueueManagerBO()
		{
			if (clientQueue == null)
				clientQueue = new ClientQueue();

			clientQueue.PropertyChanged += PropertyChangedEvent;

            //notificationTimer = new Timer(60 * 1000); // 60 Seconds
            //notificationTimer.Elapsed += new ElapsedEventHandler(NotificationTimerEvent);
            //notificationTimer.Enabled = true;
		}

		public void AddToQueue(string groupName, string clientName, string pushMessageBoxAddress)
		{
			lock (lockObject)
			{
				if (clientQueue.IsInQueue(groupName, clientName))
				{
					clientQueue.Update(groupName, clientName, pushMessageBoxAddress);
				}
				else
				{
					clientQueue.Add(new QueueItem(groupName, clientName, pushMessageBoxAddress));
				}
			}
		}

		public void SetQueuePending()
		{
			lock (lockObject)
			{
				IEnumerator<QueueItem> clientEnumerator = clientQueue.GetEnumerator();
				clientEnumerator.Reset();
				while (clientEnumerator.MoveNext())
				{
					if (clientEnumerator.Current.QueueState == QueueItem.EQueueState.eQueueStateIdle)
					{
						clientEnumerator.Current.QueueState = QueueItem.EQueueState.eQueueStatePending;
					}
				}
			}
		}

		void NotificationTimerEvent(object sender, ElapsedEventArgs e)
		{
			SetQueuePending();
		}

		void PropertyChangedEvent(object sender, PropertyChangedEventArgs e)
		{
			if (e.PropertyName == "QueueItem.QueueState.Changed")
			{
				try
				{
					QueueItem queueItem = (QueueItem)sender;

					if (queueItem.QueueState == QueueItem.EQueueState.eQueueStatePending)
					{
						PropertyChangedEventHandler handler = this.PropertyChanged;
						if (handler != null)
							handler(sender, new PropertyChangedEventArgs("QueueItem.QueueState.Pending"));
					}
				}
				catch
				{
				}
			}
		}

		#region INotifyPropertyChanged Members

		public event PropertyChangedEventHandler PropertyChanged;

		public void OnPropertyChanged(string propertyName)
		{
			PropertyChangedEventHandler handler = this.PropertyChanged;
			if (handler != null)
				handler(this, new PropertyChangedEventArgs(propertyName));
		}

		#endregion
	}
}
